// 1. 导入
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

// todo type的类型
// 好处 1. 里面字符串可以是随意的值   2. 方便阅读
export const TODO_TYPE = {
  all: 'all',
  unfinished: 'unfinished',
  finished: 'finished',
}

// 2. 导出
export const useTodoStore = defineStore('todos', () => {
  const type = ref(TODO_TYPE.all)
  const todos = ref([
    { id: 1, text: 'learn Vue3 Pinia', finished: false },
    { id: 2, text: 'play game', finished: true },
    { id: 3, text: 'watch TV', finished: true }
  ])

  // 添加
  const addTodo = (text) => {
    todos.value.push({
      id: Date.now(),
      text,
      finished: false
    })
  }

  // 删除
  const delTodo = (i) => {
    console.log(i);
    
    if (confirm('确认删除么？')) {
      todos.value.splice(i, 1)
    }
  }
  // 全选
  const checkAll = (flag) => {
    todos.value.forEach((v) => v.finished = flag)
  }
  // 清空
  const clear = () => {
    if (window.confirm('是否要清空已完成的？')) {
      todos.value = todos.value.filter((v) => !v.finished)
    }
  }
  // 设置显示状态
  const setType = (selectType) => {
    type.value = selectType
  }

  // 是否全选
  const isAll = computed(() => {
    return todos.value.every((v) => v.finished)
  })

  // 统计未完成数量
  const unFinishedCount = computed(() => {
    return todos.value.filter((v) => !v.finished).length
  })

  // 符合当前状态的列表
  const showTodos = computed(() => {
    // 依据 todos 和 type 来获取
    switch (type.value) {
      case TODO_TYPE.all:
        return todos.value
      case TODO_TYPE.unfinished:
        return todos.value.filter((v) => !v.finished)
      case TODO_TYPE.finished:
        return todos.value.filter((v) => v.finished)
    }
  })
  return {
    type,
    todos,
    isAll,
    unFinishedCount,
    showTodos,
    addTodo,
    delTodo,
    checkAll,
    clear,
    setType
  }
})